package com.leyou.comment.service;

import com.leyou.comment.config.JwtProperties;
import com.leyou.comment.mongo.CommentsMongo;
import com.leyou.comment.mapper.OrderMapper;
import com.leyou.comments.entity.Comments;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.IdWorker;
import com.leyou.order.entity.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * @author 林琼杨
 * @version 1.0
 * @date 2020/5/29 12:23
 */
@Service
@Transactional
public class CommentsService {
    @Autowired
    private CommentsMongo commentsMongo;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private JwtProperties prop;

    @Autowired
    private OrderMapper orderMapper;
    /**
     * 商品评价
     * @param comments 商品评价信息
     * @return
     */
    public void addComments(HttpServletRequest request,Comments comments){
        //获取token
        //String token = CookieUtils.getCookieValue(request, prop.getUser().getCookieName());
        //Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        //获取用户id
        //Long userId = payload.getUserInfo().getId();
        //String useridStr = userId.toString();
        //封装数据
        Date nowDate = new Date();
        //comments.setUserid(useridStr);
        comments.setPublishtime(nowDate);
        comments.set_id(idWorker.nextId()+"");
        comments.setParentid(idWorker.nextId()+"");
        //提交
        commentsMongo.save(comments);
        //修改订单状态
        Long orderIdStr = comments.getOrderid();
        //int orderId = Integer.parseInt(orderIdStr);
        //根据订单id查询订单
        Order order = orderMapper.selectByPrimaryKey(orderIdStr);
        //修改状态
        order.setStatus(6);
        //设置评价时间
        order.setCommentTime(nowDate);
        //更新订单
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 评价删除
     * @param id 评价id
     * @return
     */
    public void delComments(String id){
        commentsMongo.deleteById(id);
    }

    /**
     * 查询所有评论
     * @return
     */
    public List<Comments> findAddComments(String spuid) {
        Query query = new Query();
        Query spuidQuery = query.addCriteria(Criteria.where("spuid").is(spuid));
        List<Comments> comments = mongoTemplate.find(spuidQuery, Comments.class);
        return comments;
    }
}
